<template>
  <div>
    <div class="infinite-list-wrapper" style="overflow:auto">
      <ul
        class="list"
        v-infinite-scroll="load"
        infinite-scroll-disabled="disabled">
        <li v-for="item in visibleItems" :key="item.id" class="list-item">
          <div class="popularimg">
            <img :src="getImageUrl(item.image)" @error="handleImageError" alt="" />
          </div>
          <div class="product-name">{{item.name}}</div>
          <div class="price-goods">{{item.price}}元起</div>
        </li>
      </ul>
      <p v-if="loading">加载中...</p>
      <p v-if="noMore && visibleItems.length > 0" class="nomore">没有更多了!</p>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
	 name: 'SubtotalGoods',
  props: {
    category: {
      type: String,
      default: "猜你喜欢"
    },
    categoryId: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      shopgoodslist: [],
      visibleItems: [],
      loading: false,
      currentPage: 0,
      itemsPerLoad: 9,
      totalItems: 0,
      hasError: false
    }
  },
  computed: {
    noMore() {
      return this.visibleItems.length >= this.totalItems
    },
    disabled() {
      return this.loading || this.noMore || this.hasError
    }
  },
  watch: {
    categoryId(newVal) {
      this.resetData();
      this.fetchDataByCategory(newVal);
    }
  },
  created() {
    this.fetchDataByCategory(this.categoryId);
  },
  methods: {
    getImageUrl(relativePath) {
      return require(`@/assets/img/goods/${relativePath}`); 
    },
    handleImageError(e) {
      e.target.src = require("../assets/img/goods/dian-1.png");
    },
    resetData() {
      this.shopgoodslist = [];
      this.visibleItems = [];
      this.currentPage = 0;
      this.totalItems = 0;
    },
    fetchDataByCategory(categoryId) {
      this.loading = true;
      
      // 根据分类ID发送请求
      const apiUrl = categoryId === 0 
        ? '/products/allproducts' 
        : `/products/category/${categoryId}`;
      
      request.get(apiUrl)
        .then(res => {
          if (res.code === '200') {
            this.shopgoodslist = res.data || [];
            this.totalItems = this.shopgoodslist.length;
            this.loadInitialData();
          }
        })
        .catch(error => {
          console.error('获取商品列表失败:', error);
          this.hasError = true;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    loadInitialData() {
      const end = Math.min(this.itemsPerLoad, this.totalItems);
      this.visibleItems = this.shopgoodslist.slice(0, end);
      this.currentPage = 1;
    },
    load() {
      if (this.disabled) return;
      
      this.loading = true;
      setTimeout(() => {
        const start = this.currentPage * this.itemsPerLoad;
        const end = start + this.itemsPerLoad;
        const newItems = this.shopgoodslist.slice(start, end);
        
        this.visibleItems = [...this.visibleItems, ...newItems];
        this.currentPage++;
        this.loading = false;
      }, 500);
    }
  }
}
</script>
<style scoped>
/* 保持原有样式不变 */

.price-goods{
  color: red;
  padding-bottom: 30px;
}
.list {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -5px;
  padding: 0;
  list-style: none;
}

.list-item {
  width: calc(20% - 10px);
  margin: 0 5px 10px;
  box-sizing: border-box;
  text-align: center;
  transition: transform 0.3s ease-in-out, box-shadow 0.3s ease-in-out;
  cursor: pointer;
}
li.list-item:hover {
transform: translateY(-10px);
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.popularimg img {
  width: 100%;
  height: auto;
  max-height: 160px;
  object-fit: contain;
  padding-top: 30px;
}

.product-name {
  margin-top: 8px;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.nomore{
  text-align: center;
}
</style>